// components/profile/profile.js
import {query} from '../../utils/db'
const app = getApp()
Component({
  properties: {
    openid: {type: String}
  },

  /**
   * 组件的初始数据
   */
  data: {
    avatar: '',
    name: '',
    klass: '',
  },
  lifetimes: {
    ready() {
      query('entryForms', { _openid: this.data.openid }).then(res => {
        if (!res.length) {
          this.getGlobalUserInfo()
          return
        }
        const {avatarID, name, klass} = res[0]
        this.setData({
          avatar: avatarID,
          name: name,
          klass: `高一(${klass[0]})  高二(${klass[1]})  高三(${klass[2]})`,
        })
      })
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    queryUserInfo() {
      query('entryForms', { _openid: this.data.openid }).then(res => {
        if (!res.length) { return }
        const {avatarID, name, klass} = res[0]
        this.setData({
          avatar: avatarID,
          name: name,
          klass: `高一(${klass[0]})  高二(${klass[1]})  高三(${klass[2]})`,
        })
      })
    },
    getGlobalUserInfo() {
      const avatarUrl = app.globalData.avatarUrl
      const name = app.globalData.userInfo && app.globalData.userInfo.nickName
      this.setData({
        avatar: avatarUrl || '',
        name: name || '',
      })
    }
  }
})
